<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var xhr = new XMLHttpRequest();
    var url = "http://127.0.0.1/test/public/test.php";
    xhr.open("GET",url);
    xhr.setRequestHeader("Foo","Bar");//设置请求头信息
    //如果请求体经过urlencoded处理，需要对请求头进行下面的设置
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.send("name1=value1&name2=value2");//添加请求体，需要urlencoded处理
    xhr.onreadystatechange = function (ev) {
        //readyState状态值：0被创建，1建立连接，2send()被调用，且已获取到状态行与响应头，3响应体下载中，4数据下载完成
        if(this.readyState == 4){
            console.log(this.responseText);
        }
    };
    //onload相当于readyState为4的情况
    xhr.onload = function (ev) {
        console.log(this.responseText)
    }

    //ajax封装
    function ajax(method,url,params,done) {
        method = method.toUpperCase();
        var xhr = new XMLHttpRequest();
        xhr.open(method,url);
        var data =null;
        if(method === "POST"){
            data = params;
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        }
        xhr.onreadystatechange = function () {
            if(xhr.readyState !== 4){
                return ;
            }
            done(xhr.responseText);
        };
        xhr.send(data);
    }
</script>
</body>
</html>